package com.Drools.test;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

public class ceshi {
    static KieServices kieServices = KieServices.Factory.get();
    private static final String RULES_PATH = "rulespag/rules/";
    public static void main(String[] args) throws Exception{

        KieSession kieSession = kieContainer().getKieBase().newKieSession();
        System.out.println("--------------");
        kieSession.fireUntilHalt();
        System.out.println("--------------");
        kieSession.insert("555");
        System.out.println(kieSession.fireAllRules(1));


        kieSession.dispose();

    }
    public static KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        for (Resource file : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
            System.out.println("----------" + file.getFilename());
        }
        return kieFileSystem;
    }
    public static KieContainer kieContainer() throws IOException {
        final KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
    }
    private static Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
//        return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
        return resourcePatternResolver.getResources( RULES_PATH +"**/*.drl");
    }
}
